package web

import (
	"fmt"
	"net/http"
	"sort"

	"gitee.com/thubcc/mobile/lte"
	"gitee.com/thubcc/mobile/utils"
	"gitee.com/thubcc/rtlmmap"
	"github.com/gin-gonic/gin"
)

type LTESearchView struct {
	view utils.RFInterface
	Name string `json:"name"`
}

func NewLTESearchViewWithHandle(c *gin.Context) *LTESearchView {
	port, _ := CommonParam(c)
	config := &rtlmmap.DefaultLTEConfig
	v := rtlmmap.NewRtlView(port, config).FTV(port)
	ltev := &LTESearchView{v, c.Param("handle")}
	c.JSON(http.StatusOK, Response{*ltev, nil})
	return ltev
}

func (v *LTESearchView) ScanRef(c *gin.Context) {
	keys := []string{
		"txp",
		"n",
	}
	defaultSet := map[string]int{
		"txp": -1,
		"n":   20,
	}
	d := make([]int, 0)
	for _, v := range keys {
		d = append(d, Str1int(c.DefaultQuery(v, fmt.Sprint(defaultSet[v]))))
	}
	var res lte.ScanPeakResults
	if d[0] == -1 {
		for p := 0; p < 4; p++ {
			rp := lte.APICellPeakAll(v.view, p, d[1]/2)
			res = append(res, rp...)
		}
		sort.Sort(res)
		res = res[:d[1]]
	} else {
		res = lte.APICellPeakAll(v.view, d[0], d[1])
	}
	c.JSON(http.StatusOK, Response{res, nil})
}

func (v *LTESearchView) Channel(c *gin.Context) {
	keys := []string{
		"txp",
		"id",
		"pos",
	}
	defaultSet := map[string]int{
		"txp": 0,
		"id":  84,
		"pos": 9600,
	}
	d := make([]int, 0)
	for _, s := range keys {
		d = append(d, Str1int(c.DefaultQuery(s, fmt.Sprint(defaultSet[s]))))
	}
	r := lte.APIChannel(v.view, d[1], d[0], d[2])
	r.RxPort = Str1int(v.Name[len(v.Name)-1:])
	c.JSON(http.StatusOK, Response{r, nil})
}
